﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text;

namespace ScreenTranslate
{
    public class Message
    {

        private byte[] data = new byte[1024*1000];
        private int startIndex = 0;//我们存取了多少个字节的数据在数组里面

        //public void AddCount(int count)
        //{
        //    startIndex += count;
        //}
        public byte[] Data
        {
            get { return data; }
        }
        public int StartIndex
        {
            get { return startIndex; }
        }
        public int RemainSize
        {
            get { return data.Length - startIndex; }
        }

        /// <summary>
        /// 解析数据或者叫做读取数据
        /// </summary>
        public void ReadMessage(int newDataAmount, Action<byte[]> processDataCallback)
        {
            startIndex += newDataAmount;
            while (true)
            {
                if (startIndex <= 4) return;
                int count = BitConverter.ToInt32(data, 0);
                if ((startIndex - 4) >= count)
                {
                    byte[] bytes = new byte[count];
                    Array.Copy(data,4,bytes,0,count);
                    processDataCallback(bytes);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }
        public static byte[] PackData(byte[] bytes)
        {
            byte[] dataAmountBytes = BitConverter.GetBytes(bytes.Length);
            byte[] newBytes = dataAmountBytes.Concat(bytes).ToArray<byte>();//Concat(dataBytes);
            return newBytes;
        }
    }
}
